package cn.jeeweb.modules.server.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import cn.jeeweb.core.common.data.DuplicateValid;
import cn.jeeweb.core.model.AjaxJson;
import cn.jeeweb.core.model.PageJson;
import cn.jeeweb.core.model.ValidJson;
import cn.jeeweb.core.query.annotation.PageableDefaults;
import cn.jeeweb.core.query.data.PropertyPreFilterable;
import cn.jeeweb.core.query.data.Queryable;
import cn.jeeweb.core.query.utils.QueryableConvertUtils;
import cn.jeeweb.core.query.wrapper.EntityWrapper;
import cn.jeeweb.core.security.shiro.authz.annotation.RequiresMethodPermissions;
import cn.jeeweb.core.utils.ObjectUtils;
import cn.jeeweb.core.utils.StringUtils;
import cn.jeeweb.modules.client.style.ExcelExportStatisticStyler;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializeFilter;

import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import cn.jeeweb.core.common.controller.BaseBeanController;
import cn.jeeweb.core.security.shiro.authz.annotation.RequiresPathPermission;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

import cn.jeeweb.modules.server.entity.Order;
import cn.jeeweb.modules.server.service.IOrderService;
import cn.jeeweb.modules.sys.entity.User;
import cn.jeeweb.modules.sys.utils.UserUtils;
import org.springframework.web.multipart.MultipartFile;

/**   
 * @Title: 订单
 * @Description: 订单
 * @author zhuht
 * @date 2018-08-09 20:21:54
 * @version V1.0   
 *
 */
@Controller
@RequestMapping("${admin.url.prefix}/server/order")
@RequiresPathPermission("server:order")
public class OrderController extends BaseBeanController<Order> {

    @Autowired
    protected IOrderService orderService;

    public Order get(String id) {
        if (!ObjectUtils.isNullOrEmpty(id)) {
            return orderService.selectById(id);
        } else {
            return newModel();
        }
    }

    @RequiresMethodPermissions("list")
    @RequestMapping(method = RequestMethod.GET)
    public String list(Model model, HttpServletRequest request, HttpServletResponse response) {
        return display("list");
    }

    @RequestMapping(value = "ajaxList", method = { RequestMethod.GET, RequestMethod.POST })
    @PageableDefaults(sort = "id=desc")
    private void ajaxList(Queryable queryable, PropertyPreFilterable propertyPreFilterable, HttpServletRequest request,
                          HttpServletResponse response) throws IOException {
        EntityWrapper<Order> entityWrapper = new EntityWrapper<Order>(entityClass);
        propertyPreFilterable.addQueryProperty("id");
        // 预处理
        QueryableConvertUtils.convertQueryValueToEntityValue(queryable, entityClass);
        SerializeFilter filter = propertyPreFilterable.constructFilter(entityClass);
        PageJson<Order> pagejson = new PageJson<Order>(orderService.list(queryable,entityWrapper));
        String content = JSON.toJSONString(pagejson, filter);
        StringUtils.printJson(response, content);
    }

    @RequestMapping(value = "create", method = RequestMethod.GET)
    public String create(Model model, HttpServletRequest request, HttpServletResponse response) {
        if (!model.containsAttribute("data")) {
            model.addAttribute("data", newModel());
        }
        return display("edit");
    }

    @RequestMapping(value = "create", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson create(Model model, @Valid @ModelAttribute("data") Order order, BindingResult result,
                           HttpServletRequest request, HttpServletResponse response) {
        return doSave(order, request, response, result);
    }

    @RequestMapping(value = "{id}/update", method = RequestMethod.GET)
    public String update(@PathVariable("id") String id, Model model, HttpServletRequest request,
                              HttpServletResponse response) {
        Order order = get(id);
        model.addAttribute("data", order);
        return display("edit");
    }

    @RequestMapping(value = "{id}/update", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson update(Model model, @Valid @ModelAttribute("data") Order order, BindingResult result,
                           HttpServletRequest request, HttpServletResponse response) {
        return doSave(order, request, response, result);
    }

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson doSave(Order order, HttpServletRequest request, HttpServletResponse response,
                           BindingResult result) {
        AjaxJson ajaxJson = new AjaxJson();
        ajaxJson.success("保存成功");
        if (hasError(order, result)) {
            // 错误提示
            String errorMsg = errorMsg(result);
            if (!StringUtils.isEmpty(errorMsg)) {
                ajaxJson.fail(errorMsg);
            } else {
                ajaxJson.fail("保存失败");
            }
            return ajaxJson;
        }
        try {
            if (StringUtils.isEmpty(order.getId())) {
                orderService.insert(order);
            } else {
                orderService.insertOrUpdate(order);
            }
        } catch (Exception e) {
            e.printStackTrace();
            ajaxJson.fail("保存失败!<br />原因:" + e.getMessage());
        }
        return ajaxJson;
    }

    @RequestMapping(value = "{id}/delete", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson delete(@PathVariable("id") String id) {
        AjaxJson ajaxJson = new AjaxJson();
        ajaxJson.success("删除成功");
        try {
            orderService.deleteById(id);
        } catch (Exception e) {
            e.printStackTrace();
            ajaxJson.fail("删除失败");
        }
        return ajaxJson;
    }

    @RequestMapping(value = "batch/delete", method = { RequestMethod.GET, RequestMethod.POST })
    @ResponseBody
    public AjaxJson batchDelete(@RequestParam(value = "ids", required = false) String[] ids) {
        AjaxJson ajaxJson = new AjaxJson();
        ajaxJson.success("删除成功");
        try {
            List<String> idList = java.util.Arrays.asList(ids);
            orderService.deleteBatchIds(idList);
        } catch (Exception e) {
            e.printStackTrace();
            ajaxJson.fail("删除失败");
        }
        return ajaxJson;
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public String view(Model model, @PathVariable("id") String id, HttpServletRequest request,
                       HttpServletResponse response) {
        Order order = get(id);
        model.addAttribute("data", order);
        return display("edit");
    }

    @RequestMapping(value = "validate", method = { RequestMethod.GET, RequestMethod.POST })
    @ResponseBody
    public ValidJson validate(DuplicateValid duplicateValid, HttpServletRequest request) {
        ValidJson validJson = new ValidJson();
        Boolean valid = Boolean.FALSE;
        try {
            EntityWrapper<Order> entityWrapper = new EntityWrapper<Order>(entityClass);
            valid = orderService.doValid(duplicateValid,entityWrapper);
            if (valid) {
                validJson.setStatus("y");
                validJson.setInfo("验证通过!");
            } else {
                validJson.setStatus("n");
                if (!StringUtils.isEmpty(duplicateValid.getErrorMsg())) {
                    validJson.setInfo(duplicateValid.getErrorMsg());
                } else {
                    validJson.setInfo("当前信息重复!");
                }
            }
        } catch (Exception e) {
            validJson.setStatus("n");
            validJson.setInfo("验证异常，请检查字段是否正确!");
        }
        return validJson;
    }
    
   @RequestMapping(value = "exportExc", method = { RequestMethod.GET, RequestMethod.POST })
    @PageableDefaults(sort = "id=desc")
    private void export(Queryable queryable, PropertyPreFilterable propertyPreFilterable, HttpServletRequest request,
                          HttpServletResponse response) throws Exception {

        //单个任务
        List<ExcelExportEntity> orde = new ArrayList<ExcelExportEntity>();
        orde.add(new ExcelExportEntity("任务编号", "code"));
        ExcelExportEntity shops_name = new ExcelExportEntity("旺旺名称", "ww_name");
        shops_name.setWidth(50);
        orde.add(shops_name);
        orde.add(new ExcelExportEntity("刷单日期", "datetime"));
        orde.add(new ExcelExportEntity("金额", "price"));
        ExcelExportEntity img1 = new ExcelExportEntity("图片1", "imgpath1");
        img1.setHeight(60);
        img1.setWidth(30);
        img1.setType(2);
        img1.setExportImageType(1);
        orde.add(img1);
        ExcelExportEntity img2 = new ExcelExportEntity("图片2", "imgpath2");
        img2.setHeight(60);
        img2.setWidth(30);
        img2.setType(2);
        img2.setExportImageType(1);
        orde.add(img2);
        ExcelExportEntity img3 = new ExcelExportEntity("图片3", "imgpath3");
        img3.setHeight(60);
        img3.setWidth(30);
        img3.setType(2);
        img3.setExportImageType(1);
        orde.add(img3);
        ExcelExportEntity img4 = new ExcelExportEntity("图片4", "imgpath4");
        img4.setHeight(60);
        img4.setWidth(30);
        img4.setType(2);
        img4.setExportImageType(1);
        orde.add(img4);
        orde.add(new ExcelExportEntity("创建人姓名", "create_name"));

        EntityWrapper<Order> entityWrapper = new EntityWrapper<Order>(entityClass);
        propertyPreFilterable.addQueryProperty("id");
        // 预处理
        //entityWrapper.eq("createBy.id", UserUtils.getUser().getId());
        QueryableConvertUtils.convertQueryValueToEntityValue(queryable, entityClass);
        List<Order> orders = orderService.listWithNoPage(queryable,entityWrapper);
        //获取根路径
        ServletContext sc = request.getSession().getServletContext();
        List<Map> list = new ArrayList<Map>();
        for(Order o:orders){
            Map m = new HashMap();
            m.put("code",o.getCode());
            m.put("ww_name",o.getWwName());
            m.put("datetime",o.getDatetime());
            m.put("price",o.getPrice());
            m.put("imgpath1",sc.getRealPath("/") + o.getImgpath1());
            m.put("imgpath2",sc.getRealPath("/") + o.getImgpath2());
            m.put("imgpath3",sc.getRealPath("/") + o.getImgpath3());
            m.put("imgpath4",sc.getRealPath("/") + o.getImgpath4());
            m.put("创建人姓名",sc.getRealPath("/") + o.getCreateName());
            list.add(m);
        }
        
      //响应信息，弹出文件下载窗口
        response.setContentType("APPLICATION/OCTET-STREAM");
        response.setHeader("Content-Disposition",  "attachment; filename=" 
                        + URLEncoder.encode("任务信息-"+new SimpleDateFormat("yyyyMMddhhmmss").format(new Date())+".xlsx", "UTF-8"));  
        OutputStream os = response.getOutputStream();

        ExportParams params = new ExportParams("任务信息", "任务信息", ExcelType.XSSF);
        params.setStyle(ExcelExportStatisticStyler.class);
        Workbook workbook = ExcelExportUtil.exportExcel(params, orde, list);
        workbook.write(os);
        os.flush();
        os.close();
    }
    
    @RequestMapping(value = "updateOrder",  method = { RequestMethod.GET, RequestMethod.POST })
    @ResponseBody
    public AjaxJson updateOrder(Order order,@RequestParam("files") MultipartFile[] files, HttpServletRequest request,
                                HttpServletResponse response){
    	AjaxJson ajaxJson = new AjaxJson();
        ajaxJson.success("修改成功");

        if(order.getPrice()==null||"".equals(order.getPrice())){
            ajaxJson.fail("旺旺号不能为空!");
            return ajaxJson;
        }
        if(order.getPrice()==null||"".equals(order.getPrice())){
            ajaxJson.fail("任务标号!");
            return ajaxJson;
        }
        if(order.getPrice()==null||"".equals(order.getPrice())){
        	ajaxJson.fail("金额不能为空!");
        	return ajaxJson;
        }
        if(files.length<4){
            ajaxJson.fail("图片信息不足!");
            return ajaxJson;
        }
        
        try {
        	orderService.updateOrder(order,files,request);
        } catch (Exception e) {
            e.printStackTrace();
            ajaxJson.fail("修改失败!<br />原因:" + e.getMessage());
        }
        return ajaxJson;
    }

}
